package tableApi;

import beans.SenSorReading;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

public class tableTest01_Example {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //1.读取数据
        DataStreamSource<String> inputStream = env.readTextFile("src/main/resources/sensor.txt");
        //2.转换成POJO
        SingleOutputStreamOperator<SenSorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SenSorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });
        //3.创建表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        //4.基于流创建一张表
        Table dataTable = tableEnv.fromDataStream(dataStream);
        //5.调用tableAPI来进行转换操作
        Table resultTable = dataTable.select("id,temperature").where("id = 'sensor_1'");
        //6.直接执行sql
        tableEnv.createTemporaryView("sensor", dataTable);
        String sql = "select id ,temperature from sensor where id = 'sensor_1'";
        Table resultSql = tableEnv.sqlQuery(sql);

        //7.输出,需要先转换成流
        tableEnv.toAppendStream(resultTable, Row.class).print("print-1");
        tableEnv.toAppendStream(resultSql, Row.class).print("print-2");

        env.execute();
    }
}
